<template>
  <div>
    <el-card class="box-card" style="
          width: 500px;
          position: absolute;
          top:50%;
          left:50%;
          transform: translate(-50%,-50%);

    ">
      <div slot="header" class="clearfix">
        <span><i class="el-icon-key" style="color: orange;"></i>用户登录</span>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" suffix-icon="el-icon-user"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="checkUser">登录</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>

    </el-card>
  </div>
</template>

<script>
export default {
  name: "LoginCom",
  data() {
    return {
      form: {
        username: "anine",
        password: "123456"
      },
      //声明验证规则
      rules: {
        //用户名的校验规则
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
        ],
        //密码的校验规则
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    //校验用户名和密码是否正确
    checkUser() {
      console.info(this.form);
      this.$refs['form'].validate((valid) => {
        if (valid) {
          //往后台发送ajax请求
          this.$http.post("checkUser", this.form).then(res => {
            console.info("后台返回的数据", res);
            if (res.data.msg) {
              //先把用户对象转成json字符串
              let json = JSON.stringify(res.data.data);
              console.info(json);
              //两个参数 都是字符串类型 第一个参数是名字  第二个参数是值
              sessionStorage.setItem("session_user", json);

              this.$router.push("/index");

            } else {
              this.$message.error(res.data.error);
            }
          });
        } else {
          return false;
        }
      });


    },
    //重置表单
    resetForm() {
      this.$refs['form'].resetFields();
    }
  }
}
</script>

<style scoped>

</style>